<?php
namespace app\system\controller;

use app\common\model\AreaModel;
use org\util\TreeUtil;
use think\Request;

class AreaController extends BaseController
{

    private $areaModel;
    private $areaCache;

    /**
     * 初始化
     * AreaController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->areaModel = new AreaModel();
        $this->areaCache = cache('area');
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $pid        = $this->request->param('pid/d', 0);
        $map['pid'] = $pid;
        $area       = $this->areaModel->where($map)->order('area_sort')->select();
        $this->assign('area', $area);
        return $this->fetch();
    }

    /**
     * 添加区域
     */
    public function add()
    {
        $data   = $this->request->param();
        $result = $this->validate($data, 'AreaValidate');
        if (true !== $result) {
            $this->error($result);
        }
        $this->areaModel->addData($data);
        $this->updateCache();
        $this->success('添加成功！');
    }

    /**
     * 级联删除区域
     */
    public function del()
    {
        $area = $this->areaModel->order('area_sort')->select();
        $id       = $this->request->param('id/d');
        $ids      = [$id];
        $children = \org\util\TreeUtil::channelList($area, $id);
        foreach ($children as $v) {
            $ids[] = $v['id'];
        }
        $this->areaModel->destroy($ids);
        $this->updateCache();
        $this->success('操作成功！');
    }

    /**
     * 更新排序
     */
    public function upOrder()
    {
        $sort = $this->request->param('sort/a');
        if (!empty($sort)) {
            foreach ($sort as $k => $v) {
                $dataList[] = ['id' => (int)$k, 'area_sort' => (int)$v];
            }
            $this->areaModel->saveAll($dataList);
            $this->success('排序成功');
        } else {
            $this->error('参数错误！');
        }
    }

    public function createjs()
    {
        $this->areaModel->createJs();
        $this->areaModel->buildCityPicker();
        $this->success('同步更新成功！');
    }

    public function updateCache()
    {
        $this->areaModel->updateCache();
        $this->success('操作成功！', url('index'));
    }

}
